/**
 * 
 */
package com.wegax.finprod.validator;

import com.vaadin.data.validator.AbstractValidator;

/**
 * @author wegax
 * 
 */
class IdentityCardValidator extends AbstractValidator {

	IdentityCardValidator(String errorMessage) {
		super(errorMessage);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.vaadin.data.Validator#isValid(java.lang.Object)
	 */
	@Override
	public boolean isValid(Object value) {
		if (!(value instanceof String)) {
			return false;
		}
		String id = (String) value;
		if (id.length() != 9) {
			return false;
		}
		int checkSum;
		checkSum = 7 * getLetterValue(id.charAt(0));
		checkSum += 3 * getLetterValue(id.charAt(1));
		checkSum += 1 * getLetterValue(id.charAt(2));
		checkSum += 7 * getLetterValue(id.charAt(4));
		checkSum += 3 * getLetterValue(id.charAt(5));
		checkSum += 1 * getLetterValue(id.charAt(6));
		checkSum += 7 * getLetterValue(id.charAt(7));
		checkSum += 3 * getLetterValue(id.charAt(8));
		checkSum %= 10;
		return checkSum == getLetterValue(id.charAt(3));
	}

	static char letterValues[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
			'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

	private static int getLetterValue(char letter) {
		int i;
		for (i = 0; i < letterValues.length; i++) {
			if (letter == letterValues[i]) {
				return i;
			}
		}
		return -1;
	}

}
